import processing.core.*;
import wordcram.*;
import wordcram.text.StopWords;

public class TagCloud extends GuiElement{
		
	public WordCram wc;
	PGraphics buffer;
		
	public String lyrics;
	public FillBufferThread thread;
	
	public boolean loaded;
	
	public TagCloud(String lyrics, float xValue, float yValue, float WEIGHT, float HEIGHT) {
	
		x = xValue;
		y = yValue;
		
		width = WEIGHT;
		height = HEIGHT;		
		this.lyrics = lyrics;
		
		loaded = false;
						
		setTagCloud();

	}
	
	public void setTagCloud() {
				

		buffer = GLOBAL.processing.createGraphics((int)width, (int)height, GLOBAL.processing.JAVA2D);
		buffer.beginDraw();
		buffer.background(GLOBAL.colorBackground); 
				
		wc = new WordCram(GLOBAL.processing)
					.fromTextString(lyrics)
					.withCustomCanvas(buffer)
					.withColors(GLOBAL.COLORS.getArray())
					.sizedByWeight(6,60).withWordPadding(3)
					.withAngler(Anglers.horiz())
					.withPlacer(Placers.centerClump())
					.maxNumberOfWordsToDraw(60)
					.withStopWords(StopWords.ENGLISH)
					.maxAttemptsToPlaceWord(10000);
		
		thread = new FillBufferThread();
				
	}

	public void draw() {

		if (GLOBAL.songsSelected.size() == 0)
			return;
		
		if (loaded)
			GLOBAL.processing.image(buffer, x, y);
		
	}
	
	public void updateTagCloud() {
		if (thread.isAlive()) thread.stop();
		thread = new FillBufferThread();
		thread.run();
	}
	
	public void changePosition(float xValue, float yValue, float w, float l) {
		
		x = xValue;
		y = yValue;
		
		width = w;
		height = l;
				
		buffer.width = (int) width;
		buffer.height = (int) height;
		
		setTagCloud();
		
	}
	
	public class FillBufferThread extends Thread{
		
		public void run() {
			boolean lyrics = false;
			for(Song s: GLOBAL.songsSelected){
				if(s.lyrics_found){
					lyrics = true;
					break;
				}
			}
			if(!lyrics) return;

			try{
				wc.drawAll();
				buffer.endDraw();
				loaded = true;
			}
			catch(Exception e){
				if (wc.getWords().length < 60)
					wc.maxNumberOfWordsToDraw(wc.getWords().length);

				wc.drawAll();
				buffer.endDraw();
				loaded = true;
			}
		}
		
	}

}